﻿Imports System.Threading
Imports Microsoft.ServiceHosting.ServiceRuntime
Imports Microsoft.Samples.ServiceHosting.StorageClient

Public Class WorkerRole
    Inherits RoleEntryPoint

  Public Overrides Sub Start()
    ' This is a sample implementation for Emmanuel_WorkerRole. Replace with your logic.
    RoleManager.WriteToLog("Information", "Worker Process entry point called.")

    While (True)
      Thread.Sleep(10000)

      If Not (bParametersLoaded) Then bParametersLoaded = LoadParameters()
      If bParametersLoaded Then Call CheckSystemEvents()

      'RoleManager.WriteToLog("Information", "Working")
    End While

  End Sub

  Public Overrides Function GetHealthStatus() As RoleStatus
    ' This is a sample worker implementation. Replace with your logic.
    'GetHealthStatus = RoleStatus.Healthy
    Return oRoleStatus
  End Function

  Public Sub CheckSystemEvents()
    Dim bReturn As Boolean = True
    Dim oMessage As Message = Nothing

    Try
      If oMessageQueue.DoesQueueExist() Then
        oMessage = oMessageQueue.GetMessage()
        While oMessage IsNot Nothing
          If oMessage IsNot Nothing Then
            bReturn = HandleMessage(oMessage)
            If bReturn Then oMessageQueue.DeleteMessage(oMessage)
          End If

          Try
            oMessage = oMessageQueue.GetMessage()
          Catch ex As Exception
            oMessage = Nothing
          End Try
        End While
        oMessage = Nothing
      Else
        oMessageQueue.CreateQueue()
      End If

    Catch ex As Exception
      LogMessage("Error while processing queue in CheckSystemEvents(): " + ex.ToString, EventLogEntryType.Error)
    End Try
  End Sub
  Function HandleMessage(ByVal oMessage As Message) As Boolean
    Dim bReturn As Boolean = False
    Dim sMessage As String = ""

    Try
      sMessage = oMessage.ContentAsString()
      Call LogMessage("Got Message in queue: " + sMessage, EventLogEntryType.Error)

      bReturn = True
    Catch ex As Exception
      bReturn = False
    End Try

    Return bReturn
  End Function
End Class
